﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SalaryChannel.SupportService;
using System.Collections.ObjectModel;

namespace SalaryChannel
{
    public partial class ChannelSupport : UserControl
    {
        public ChannelSupport()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(ChannelSupport_Loaded);
            ServiceInstance.SupportSerivce.GetDepartmentCompleted += new EventHandler<SalaryChannel.SupportService.GetDepartmentCompletedEventArgs>(SupportSerivce_GetDepartmentCompleted);

            //ChannelCBox0.SelectionChanged += new SelectionChangedEventHandler(ChannelCBox0_SelectionChanged);
            this.BigTab.SelectionChanged += new SelectionChangedEventHandler(BigTab_SelectionChanged);

            ServiceInstance.SupportSerivce.GetUserByDepartmentCompleted += new EventHandler<SalaryChannel.SupportService.GetUserByDepartmentCompletedEventArgs>(SupportSerivce_GetUserByDepartmentCompleted);

            ServiceInstance.SupportSerivce.CreateWorkListCompleted += new EventHandler<SalaryChannel.SupportService.CreateWorkListCompletedEventArgs>(SupportSerivce_CreateWorkListCompleted);

            ServiceInstance.SupportSerivce.GetWorkListCompleted += new EventHandler<SalaryChannel.SupportService.GetWorkListCompletedEventArgs>(SupportSerivce_GetWorkListCompleted);

            ServiceInstance.SupportSerivce.GetWorkStepCompleted += new EventHandler<SalaryChannel.SupportService.GetWorkStepCompletedEventArgs>(SupportSerivce_GetWorkStepCompleted);
            ServiceInstance.SupportSerivce.GetWorkBodyCompleted += new EventHandler<SalaryChannel.SupportService.GetWorkBodyCompletedEventArgs>(SupportSerivce_GetWorkBodyCompleted);
            ServiceInstance.SupportSerivce.GetMyWorkCompleted += new EventHandler<SalaryChannel.SupportService.GetMyWorkCompletedEventArgs>(SupportSerivce_GetMyWorkCompleted);

            ServiceInstance.SupportSerivce.FinishMyWorkCompleted += new EventHandler<FinishMyWorkCompletedEventArgs>(SupportSerivce_FinishMyWorkCompleted);
        }


        void BigTab_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (BigTab.SelectedItem != null)
            {
                if (BigTab.SelectedItem.Equals(MyWorkPage))
                {
                    this.InitMyWorkPage();
                }
            }
            this.FlowPage.Tag = null;
            this.ProcessGrid.Tag = null;
        }


        void ChannelSupport_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        public void Initiallize()
        {
            this.CreatePage.Visibility = App.IsAuth(13) ? Visibility.Visible : Visibility.Collapsed;

            ClearCreateList();
            ClearList1();
            this.BodyTB2.Text = "请选择一个工单";
            this.StepGrid.ItemsSource = null;
            this.MyWorkListGrid.ItemsSource = null;
            this.ProcessGrid.Tag = null;
            this.FlowPage.Tag = null;
            if (((FlowPage.RenderTransform as TransformGroup).Children[3] as TranslateTransform).Y != -500)
            {
                ((FlowPage.RenderTransform as TransformGroup).Children[3] as TranslateTransform).Y = -500;
                IsInforBoxIn = true;
            }

            if (ChannelCBox0.Items.Count == 0)
            {

                try
                {
                    ServiceInstance.SupportSerivce.GetDepartmentAsync();
                    // ServiceInstance.SupportSerivce.GetListTypeAsync();
                }
                catch
                {
                }
            }

        }

        #region 创建工单
        void SupportSerivce_GetDepartmentCompleted(object sender, SalaryChannel.SupportService.GetDepartmentCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    ChannelCBox0.Items.Clear();
                    foreach (var q in e.Result)
                    {
                        ChannelCBox0.Items.Add(q);
                    }
                }
            }
            catch
            {
            }
        }

        void ChannelCBox0_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(ChannelCBox0.SelectedText))
            {
                try
                {
                    ServiceInstance.SupportSerivce.GetUserByDepartmentAsync(
                              DataHelper.GetIDOFIDAndName(ChannelCBox0.SelectedText).ToString(), "CreatePage");
                }
                catch
                {
                    App.MessageBox.ShowDialog("连接服务器失败");
                }
            }
        }

        void SupportSerivce_GetUserByDepartmentCompleted(object sender, SalaryChannel.SupportService.GetUserByDepartmentCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取员工信息失败");
                }
                else
                {
                    if (e.UserState == null)
                    {
                    }
                    else if (e.UserState.Equals("CreatePage"))
                    {
                    }
                    else if (e.UserState.Equals("ProcessGrid"))
                    {
                    }
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("获取员工信息失败");
            }

        }

        private void ClearCreateList()
        {
            this.SubjectTB0.Text = string.Empty;
            this.ChannelCBox0.SelectedIndex = -1;
            this.Body0TB.Text = string.Empty;
        }

        private void ClearBtn0_Click(object sender, RoutedEventArgs e)
        {
            ClearCreateList();
        }

        private void OKBtn0_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(SubjectTB0.Text.Trim())
                || string.IsNullOrEmpty(ChannelCBox0.SelectedText)
                || string.IsNullOrEmpty(Body0TB.Text))
            {
                App.MessageBox.ShowDialog("请完整填写各项信息");
                return;
            }

            if (Body0TB.Text.Length > 250)
            {
                App.MessageBox.ShowDialog("内容过长，请不要超过250个汉字");
                return;
            }

            try
            {
                ServiceInstance.SupportSerivce.CreateWorkListAsync(
                       App.CurrentUser.UserID,
                       this.SubjectTB0.Text.Trim(),
                       this.Body0TB.Text,
                       DataHelper.GetIDOFIDAndName(ChannelCBox0.SelectedText).ToString());
                this.OKBtn0.IsEnabled = false;
            }
            catch
            {
                this.OKBtn0.IsEnabled = true;
                App.MessageBox.ShowDialog("连接服务器失败");
            }

        }


        void SupportSerivce_CreateWorkListCompleted(object sender, SalaryChannel.SupportService.CreateWorkListCompletedEventArgs e)
        {
            try
            {
                this.OKBtn0.IsEnabled = true;
                if (e.Result)
                {
                    App.MessageBox.ShowDialog("创建成功");
                    ClearCreateList();
                }
                else
                {
                    App.MessageBox.ShowDialog("创建失败，请稍后重试");
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("获取操作结果失败");
            }
        }
        #endregion

        #region 工单查询

        private void ClearList1()
        {
            this.SubjectTB1.Text = string.Empty;
            this.ListGrid1.ItemsSource = null;

            _pageIndex = -1;
            start = DateTime.Parse("2000-01-01");
            end = DateTime.Parse("9000-01-01");
            subject = string.Empty;
            userID = string.Empty;

        }

        private readonly int PageSize = 10;
        private int _pageIndex = -1;
        private int PageIndex
        {
            set
            {
                if (value > 0 && value != _pageIndex)
                {
                    lock (this)
                    {
                        _pageIndex = value;
                        GotoPage(_pageIndex);
                        this.PageIndexTB.Text = _pageIndex.ToString();
                    }
                }
            }
            get
            {
                return _pageIndex;
            }
        }
        DateTime start = DateTime.Parse("2000-01-01");
        DateTime end = DateTime.Parse("9000-01-01");
        string subject = string.Empty;
        string userID = string.Empty;
        private void OKBtn1_Click(object sender, RoutedEventArgs e)
        {

            if (DateCB1.IsChecked.Value)
            {
                try
                {
                    start = DateTime.Parse(StartDPicker.Text);
                    end = DateTime.Parse(EndDPicker.Text);
                }
                catch
                {
                    App.MessageBox.ShowDialog("请选择查询日期");
                    return;
                }
                if (end < start)
                {
                    App.MessageBox.ShowDialog("结束日期不于小于开始日期");
                    return;
                }
                end = DateTime.Parse(EndDPicker.Text + " 23:59:59");
            }
            subject = this.SubjectTB1.Text.Trim();
            _pageIndex = 0;
            PageIndex = 1;

        }

        private void GotoPage(int pageIndex)
        {
            try
            {
                this.OKBtn1.IsEnabled = false;
                this.PageIndexTB.IsReadOnly = true;
                ServiceInstance.SupportSerivce.GetWorkListAsync(subject,
                    App.IsAuth(13) ? string.Empty : App.CurrentUser.ChannelID,
                    start, end, pageIndex, PageSize);
                Loading1.Show();
            }
            catch
            {
                Loading1.Stop();
                this.OKBtn1.IsEnabled = true;
                this.PageIndexTB.IsReadOnly = false;
                App.MessageBox.ShowDialog("连接服务器失败");
            }
        }

        void SupportSerivce_GetWorkListCompleted(object sender, SalaryChannel.SupportService.GetWorkListCompletedEventArgs e)
        {
            try
            {

                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取查询数据失败");
                }
                else
                {
                    this.ListGrid1.ItemsSource = e.Result;
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("获取查询数据失败");
            }
            finally
            {
                Loading1.Stop();
                this.OKBtn1.IsEnabled = true;
                this.PageIndexTB.IsReadOnly = false;
            }
        }
        private void Next_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if ((ListGrid1.ItemsSource as ObservableCollection<VW_UserWorkList>)?.Count == PageSize)
            {
                PageIndex++;
            }
        }

        private void PageIndexTB_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                int index = -1;
                if (!int.TryParse(PageIndexTB.Text, out index))
                {
                    App.MessageBox.ShowDialog("请输入大于1的整数");
                    return;
                }
                if (index > 0)
                {
                    PageIndex = index;
                }
            }
        }

        private void Pre_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (PageIndex > 1)
            {
                PageIndex--;
            }
        }


        // private SupportService.VW_UserWorkList SelectedList = null;
        private void ListGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SupportService.VW_UserWorkList SelectedList = null;
            if (ListGrid1.SelectedItem != null)
            {
                SelectedList = ListGrid1.SelectedItem as SupportService.VW_UserWorkList;
            }
            else
            {
                SelectedList = null;
            }
            this.selectListNameTB.Text = SelectedList == null ? string.Empty : SelectedList.Subject;

        }

        /// <summary>
        /// 查看选中的行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            if (tb.Tag != null)
            {
                try
                {
                    InitStepPage(int.Parse(tb.Tag.ToString()));
                }
                catch
                {
                    App.MessageBox.ShowDialog("获取选中的ID失败");
                }
            }
        }
        #endregion

        #region 工单流程

        private bool IsInforBoxIn = true;

        void ShowOrHideFlowPage()
        {
            if (!IsInforBoxIn)
            {

                PageOutSB.Begin();
                this.PageOutSB.Completed += (s, e) =>
                {
                    PageOutSB.Stop();
                    this.FlowPage.Visibility = Visibility.Collapsed;

                };
                IsInforBoxIn = !IsInforBoxIn;
            }
            else
            {
                this.FlowPage.Visibility = Visibility.Visible;
                this.PageInSB.Begin();

                IsInforBoxIn = !IsInforBoxIn;
            }
        }

        void InitStepPage(int WorkID)
        {
            lock (this)
            {
                //  this.FlowPage.Visibility = Visibility.Visible;
                ShowOrHideFlowPage();

                if (WorkID == -1)
                {
                    this.BodyTB2.Text = "请选择一个工单";
                    this.StepGrid.ItemsSource = null;
                }
                else
                {
                    if (this.FlowPage.Tag == null
                        || !this.FlowPage.Tag.Equals(WorkID))
                    {
                        //this.BodyTB2.Text = SelectedList.Subject;
                        try
                        {
                            ServiceInstance.SupportSerivce.GetWorkStepCompleted += new EventHandler<SalaryChannel.SupportService.GetWorkStepCompletedEventArgs>(SupportSerivce_GetWorkStepCompleted);
                            ServiceInstance.SupportSerivce.GetWorkBodyCompleted += new EventHandler<SalaryChannel.SupportService.GetWorkBodyCompletedEventArgs>(SupportSerivce_GetWorkBodyCompleted);


                            ServiceInstance.SupportSerivce.GetWorkBodyAsync(WorkID);
                            ServiceInstance.SupportSerivce.GetWorkStepAsync(WorkID);

                            this.FlowPage.Tag = WorkID;
                            this.flowLoading.Show();
                        }
                        catch
                        {
                            this.flowLoading.Stop();
                            this.FlowPage.Tag = null;
                            ServiceInstance.SupportSerivce.GetWorkStepCompleted -= new EventHandler<SalaryChannel.SupportService.GetWorkStepCompletedEventArgs>(SupportSerivce_GetWorkStepCompleted);
                            ServiceInstance.SupportSerivce.GetWorkBodyCompleted -= new EventHandler<SalaryChannel.SupportService.GetWorkBodyCompletedEventArgs>(SupportSerivce_GetWorkBodyCompleted);

                            App.MessageBox.ShowDialog("连接服务器失败");
                        }
                    }
                }
            }

        }
        void SupportSerivce_GetWorkBodyCompleted(object sender, SalaryChannel.SupportService.GetWorkBodyCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    this.BodyTB2.Text = "获取数据失败";
                }
                else
                {
                    this.BodyTB2.Text = e.Result;
                }
            }
            catch
            {
                this.BodyTB2.Text = "获取数据失败";
            }
            finally
            {
                ServiceInstance.SupportSerivce.GetWorkBodyCompleted -= new EventHandler<SalaryChannel.SupportService.GetWorkBodyCompletedEventArgs>(SupportSerivce_GetWorkBodyCompleted);

            }
        }

        void SupportSerivce_GetWorkStepCompleted(object sender, SalaryChannel.SupportService.GetWorkStepCompletedEventArgs e)
        {
            try
            {
                this.flowLoading.Stop();
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取查询结果失败");
                }
                else
                {
                    StepGrid.ItemsSource = e.Result;
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("获取查询结果失败");
            }
            finally
            {
                ServiceInstance.SupportSerivce.GetWorkStepCompleted -= new EventHandler<SalaryChannel.SupportService.GetWorkStepCompletedEventArgs>(SupportSerivce_GetWorkStepCompleted);

            }
        }
        private void ReturnBtn_Click(object sender, RoutedEventArgs e)
        {
            //this.FlowPage.Visibility = Visibility.Collapsed;
            ShowOrHideFlowPage();
        }

        #endregion

        #region 待处理工单

        private void ClearProcessGrid()
        {
            this.OpinionTB.Text = string.Empty;
            ProcessGrid.Tag = null;
            this.RBtnDeal.IsChecked = true;
            //  CurWorkCreaterID = string.Empty;
        }

        private void InitMyWorkPage()
        {
            try
            {
                ServiceInstance.SupportSerivce.GetMyWorkAsync(App.CurrentUser.ChannelID);
                this.myWorkLoading.Show();
                this.RefreshBtn.IsEnabled = false;
                this.MyWorkPage.Tag = App.CurrentUser.UserID;
            }
            catch
            {
                this.myWorkLoading.Stop();
                this.RefreshBtn.IsEnabled = true;
                App.MessageBox.ShowDialog("连接服务器失败");
            }
        }

        void SupportSerivce_GetMyWorkCompleted(object sender, SalaryChannel.SupportService.GetMyWorkCompletedEventArgs e)
        {
            try
            {
                this.myWorkLoading.Stop();
                this.RefreshBtn.IsEnabled = true;
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取待处理工单失败");
                }
                else
                {
                    this.MyWorkListGrid.ItemsSource = e.Result;
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("获取待处理工单失败");
            }
        }

        private void RefreshBtn_Click(object sender, RoutedEventArgs e)
        {
            InitMyWorkPage();
        }
        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBlock2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            if (tb.Tag != null)
            {
                try
                {
                    this.InitStepPage(int.Parse(tb.Tag.ToString()));
                }
                catch
                {
                    App.MessageBox.ShowDialog("获取选中行ID失败");
                }
            }
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBlock3_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.ProcessGrid.Visibility = Visibility.Visible;
            ClearProcessGrid();
            // List<VW_UserWorkList> myWork = MyWorkListGrid.ItemsSource as List<VW_UserWorkList>;
            //var query = from q in myWork
            //            where q.StepID == int.Parse((sender as TextBlock).Tag.ToString())
            //            select q;
            //VW_Su_MyWork work = query.First();
            //  CurWorkCreaterID = work.CreateID;
            ProcessGrid.Tag = (sender as TextBlock).Tag;
        }
        // string CurWorkCreaterID = string.Empty;

        private void Clear4Btn_Click(object sender, RoutedEventArgs e)
        {
            this.ProcessGrid.Visibility = Visibility.Collapsed;
        }

        private void OK4Btn_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(OpinionTB.Text))
            {
                App.MessageBox.ShowDialog("请输入处理意见");
                return;
            }


            try
            {
                ServiceInstance.SupportSerivce.FinishMyWorkAsync(
                    (int)ProcessGrid.Tag,
                    App.CurrentUser.UserID,
                    RBtnDeal.IsChecked == true,
                    OpinionTB.Text);
                this.OK4Btn.IsEnabled = false;
                this.Cursor = Cursors.Wait;
            }
            catch (Exception ex)
            {
                this.OK4Btn.IsEnabled = true;
                this.Cursor = Cursors.Arrow;
                App.MessageBox.ShowDialog(ex.Message);
                return;
            }
        }

        void SupportSerivce_FinishMyWorkCompleted(object sender, FinishMyWorkCompletedEventArgs e)
        {
            try
            {
                if (e.Result)
                {
                    App.MessageBox.ShowDialog("提交成功");
                    ProcessGrid.Visibility = Visibility.Collapsed;
                    RefreshBtn_Click(null, null);
                }
                else
                {
                    App.MessageBox.ShowDialog("提交失败，请稍后再试");
                }
            }
            catch
            {

                App.MessageBox.ShowDialog("提交成功");
            }
            finally
            {
                this.OK4Btn.IsEnabled = true;
                this.Cursor = Cursors.Arrow;
            }
        }


        #endregion


    }
}
